﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Kgb.Model.Models;
using Kgb.Web2.Repository;
using Kgb.Web2.Util;

namespace Kgb.Web2.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            ViewBag.Message = "Bem vindo ao game KGB (Detetive)";

            return View();
        }

        public ActionResult About()
        {
            ViewBag.Message = "Your quintessential app description page.";

            return View();
        }

        public ActionResult Contact()
        {
            ViewBag.Message = "Your quintessential contact page.";

            return View();
        }

        public ActionResult Regras()
        {
            ViewBag.Message = "regras page.";

            return View();
        }

        //
        // GET: /Home/PlayGame

        [AllowAnonymous]
        public ActionResult PlayGame()
        {
            return ContextDependentView();
        }

        //
        // POST: /Home/JsonPlayGame

        [AllowAnonymous]
        [HttpPost]
        public ActionResult JsonPlayGame(Player player)
        {
            if (ModelState.IsValid)
            {
                Player p;
                if (Session["player"] == null)
                {
                    p = new Player(player.Name, Guid.NewGuid().ToString());
                    Session.Add("player", p);
                }
                else
                {
                    p = Session["player"] as Player;
                    p.Name = player.Name;
                }

                if (string.IsNullOrEmpty(p.Session()))
                    p.SessionId = Guid.NewGuid().ToString();

                p.State = "lobby";
                p.RoomId = null;
                p.LobbyId = 1; // O valor 1 foi forçado, pois não iremos criar uma tela
                // de escolha de lobby. Todos os jogadores irão cair diretamente
                // na tela do lobby 1 que terá uma lista de salas disponíveis.

                PlayerRepository repository = new PlayerRepository(new JsonNetSerialization());

                try
                {
                    if (p.Id > 0)
                    {
                        repository.Delete(p.Id); // Teste, remover depois!! tem que criar uma opção de desconexão com o jogo.
                        p.Id = 0;
                    }
                    p = repository.Create(p);

                    //return Json(p);

                    return Json(new { success = true, redirect = "Game/Lobby/1"});
                }
                catch (Exception ex)
                {
                    ModelState.AddModelError("", ex.Message);
                }
            }

            // If we got this far, something failed
            return Json(new { errors = GetErrorsFromModelState() });
        }

        // POST: /Home/PlayGame

        [AllowAnonymous]
        [HttpPost]
        public ActionResult PlayGame(Player player)
        {
            if (ModelState.IsValid)
            {


                //// Attempt to register the user
                //MembershipCreateStatus createStatus;
                //Membership.CreateUser(model.UserName, model.Password, model.Email, passwordQuestion: null, passwordAnswer: null, isApproved: true, providerUserKey: null, status: out createStatus);

                //if (createStatus == MembershipCreateStatus.Success)
                //{
                //    FormsAuthentication.SetAuthCookie(model.UserName, createPersistentCookie: false);
                //    return RedirectToAction("Index", "Home");
                //}
                //else
                //{
                //    ModelState.AddModelError("", ErrorCodeToString(createStatus));
                //}
            }

            // If we got this far, something failed, redisplay form
            return View(player);
        }

        private ActionResult ContextDependentView()
        {
            string actionName = ControllerContext.RouteData.GetRequiredString("action");
            if (Request.QueryString["content"] != null)
            {
                ViewBag.FormAction = "Json" + actionName;
                return PartialView();// (actionName);
            }
            else
            {
                ViewBag.FormAction = actionName;
                return View();
            }
        }

        private IEnumerable<string> GetErrorsFromModelState()
        {
            return ModelState.SelectMany(x => x.Value.Errors.Select(error => error.ErrorMessage));
        }
    }
}
